package com.example.jh352160.surfingtv.category;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.example.jh352160.surfingtv.R;
import com.example.jh352160.surfingtv.category.customView.CategoryList;
import com.example.jh352160.surfingtv.category.customView.Subscribe_item;
import com.example.jh352160.surfingtv.category.customView.adapter.PagerAdapter;
import com.example.jh352160.surfingtv.category.customView.adapter.SubscribeListAdapter;
import com.example.jh352160.surfingtv.network.item.CategoryItem;
import com.example.jh352160.surfingtv.network.item.CategoryListItem;
import com.example.jh352160.surfingtv.network.retrofit.CommonRetrofit;
import com.example.jh352160.surfingtv.network.service.CategoryListService;
import com.example.jh352160.surfingtv.network.service.CategoryService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by jh352160 on 2016/7/25
 */

public class Category_main extends Fragment {

    public static final int NETWORK_OK = 0, LIST_NETWORK_OK = 1, LIST_LOAD_MORE_OK = 2;
    ImageView expandImage;
    ViewPager categoryPager;
    ListView subscribeList;
    List<Map<String, Object>> datas;
    List<CategoryList> categoryLists;
    Boolean isCategoryShow;
    List<Subscribe_item> subscribe_items;
    View view;
    List<String> nameList, imageList, quantityList;
    List<Integer> categoryIdList;
    List<Boolean> isSubscribed;
    List<String> titleList, summaryList, imageUrlList, detailUrlList;
    List<Integer> favoriteCountList;
    List<Boolean> isfavoriteList;
    List<Integer> contentIdList;
    SwipeToLoadLayout swipeToLoadLayout;
    int count = 0;
    int position = 0;
    public static List<Integer> thematicList;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NETWORK_OK:
                    networkInit();
                    break;
                case LIST_NETWORK_OK:
                    newList();
                    break;
                case LIST_LOAD_MORE_OK:
                    listInit();
                    break;
            }
        }
    };

    public Category_main() {
    }

    public static Category_main newInstance() {
        return new Category_main();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = inflater.inflate(R.layout.category_page, container, false);
        thematicList = new ArrayList<>();
        swipeToLoadLayout = (SwipeToLoadLayout) view.findViewById(R.id.loadMore);
        count = 0;
        position = 0;
        subscribe_items = new ArrayList<>();


        init();

        swipeToLoadLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... voids) {
                        Message message = new Message();
                        message.what = LIST_LOAD_MORE_OK;
                        handler.sendMessage(message);
                        count += 5;
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        swipeToLoadLayout.setLoadingMore(false);
                    }
                }.execute();
            }
        });

        isCategoryShow = true;
        return view;
    }

//    @Override
//    public void onResume() {
//        init();
//        isCategoryShow=true;
//        super.onResume();
//    }

    private void init() {
        expandImage = (ImageView) view.findViewById(R.id.expandImage);
        categoryPager = (ViewPager) view.findViewById(R.id.categoryPager);
        subscribeList = (ListView) view.findViewById(R.id.swipe_target);
//        int[] images={R.drawable.category_image1,R.drawable.category_image2,R.drawable.category_image3,R.drawable.category_image4,R.drawable.category_image5,R.drawable.category_image6};
//        String[] titles={"Name 1","Name 2","Name 3","Name 4","Name 5","Name 6"};

        //EventBus
        EventBus.getDefault().register(this);

        //api
        Retrofit retrofit = CommonRetrofit.getRetrofit();
        CategoryService categoryService = retrofit.create(CategoryService.class);
        Call<CategoryItem> call = categoryService.getItem();
        call.enqueue(new Callback<CategoryItem>() {
            @Override
            public void onResponse(Call<CategoryItem> call, Response<CategoryItem> response) {
                nameList = new ArrayList<>();
                imageList = new ArrayList<>();
                quantityList = new ArrayList<>();
                categoryIdList = new ArrayList<>();
                isSubscribed = new ArrayList<>();
                List<CategoryItem.DataBean.SubjectCategorysBean> subjectCategorysBeanList = response.body().getData().getSubjectCategorys();
                for (int i = 0; i < subjectCategorysBeanList.size(); i++) {
                    nameList.add(subjectCategorysBeanList.get(i).getCategoryName());
                    imageList.add(subjectCategorysBeanList.get(i).getImageUrl());
                    quantityList.add(subjectCategorysBeanList.get(i).getQuantity() + "");
                    categoryIdList.add(subjectCategorysBeanList.get(i).getCategoryId());
                    isSubscribed.add(subjectCategorysBeanList.get(i).isSubscribed());
                }
                Message message = new Message();
                message.what = NETWORK_OK;
                handler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<CategoryItem> call, Throwable t) {
                Log.e("Retrofit Error", t.toString());
            }
        });
    }

    private void networkInit() {
        datas = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("imageId", imageList.get(i));
            map.put("title", nameList.get(i));
            map.put("quantity", quantityList.get(i));
            map.put("categoryId", categoryIdList.get(i));
            map.put("isSubscribed", isSubscribed.get(i));
            datas.add(map);
        }
        List<Map<String, Object>> maps = new ArrayList<>();
        categoryLists = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            maps.add(datas.get(i - 1));
            if (i % 4 == 0 || i == datas.size()) {
                CategoryList categoryList = new CategoryList(this.getActivity(), maps);
                categoryLists.add(categoryList);
                maps = new ArrayList<>();
            }
        }
        PagerAdapter adapter = new PagerAdapter(categoryLists);
        categoryPager.setAdapter(adapter);

        expandImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCategoryShow) {
                    expandImage.setImageResource(R.drawable.category_hide);
                    categoryPager.setVisibility(View.GONE);
                    isCategoryShow = false;
                } else {
                    expandImage.setImageResource(R.drawable.category_show);
                    categoryPager.setVisibility(View.VISIBLE);
                    isCategoryShow = true;
                }
            }
        });

        listFlush();
    }

    private void newList() {
        synchronized (this) {
            //thematicList = new ArrayList<>();
            subscribe_items = new ArrayList<>();
            listInit();
        }
    }

    private void listInit() {

//        String[] titles={"专题1","专题2","专题3","专题4"};
//        String[] abouts={"简介1","简介2","简介3","简介4"};
//        subscribe_items=new ArrayList<>();
//        for(int i=0;i< titles.length;i++){
//            Subscribe_item subscribe_item=new Subscribe_item(this.getActivity());
//            subscribe_item.setData(titles[i],abouts[i],);
//            subscribe_items.add(subscribe_item);
//        }
//        SubscribeListAdapter adapter=new SubscribeListAdapter(this.getActivity(),R.layout.category_subscribe_item,subscribe_items);
//        subscribeList.setAdapter(adapter);

        //subscribe_items=new ArrayList<>();
        for (int i = count; i + count < titleList.size() && i < count + 5; i++) {
            //for(int i=0;i<1;i++){
            Subscribe_item subscribe_item = new Subscribe_item(this.getActivity());
            subscribe_item.setData(titleList.get(i), summaryList.get(i), imageUrlList.get(i), detailUrlList.get(i), favoriteCountList.get(i), isfavoriteList.get(i), contentIdList.get(i));
            subscribe_items.add(subscribe_item);
        }
        //count+=5;
        position = subscribeList.getFirstVisiblePosition();
        SubscribeListAdapter adapter = new SubscribeListAdapter(this.getActivity(), R.layout.category_subscribe_item, subscribe_items);
        subscribeList.setAdapter(adapter);
        subscribeList.setSelection(position);
    }

    public void listFlush() {

//        final List<CategoryListItem.DataBean.ItemsBean> totalItems = new ArrayList<>();
        titleList = new ArrayList<>();
        summaryList = new ArrayList<>();
        imageUrlList = new ArrayList<>();
        detailUrlList = new ArrayList<>();
        isfavoriteList = new ArrayList<>();
        contentIdList = new ArrayList<>();
        favoriteCountList = new ArrayList<>();

        for (int i : thematicList) {
            //api
            Retrofit retrofit = CommonRetrofit.getRetrofit();
            CategoryListService categoryListService = retrofit.create(CategoryListService.class);
            Call<CategoryListItem> call = categoryListService.getItem(i);
            call.enqueue(new Callback<CategoryListItem>() {
                @Override
                public void onResponse(Call<CategoryListItem> call, Response<CategoryListItem> response) {
                    if (response.body().getData() != null) {
                        List<CategoryListItem.DataBean.ItemsBean> items = response.body().getData().getItems();
//                        totalItems.addAll(items);
                        for (int i = 0; i < items.size(); i++) {
                            titleList.add(items.get(i).getTitle());
                            summaryList.add(items.get(i).getSummary());
                            imageUrlList.add(items.get(i).getImageUrl());
                            detailUrlList.add(items.get(i).getDetailUrl());
                            isfavoriteList.add(items.get(i).getFavorite() == 1);
                            favoriteCountList.add(items.get(i).getFavoriteCount());
                            contentIdList.add(items.get(i).getContentId());
                        }
                    }
                    Message message = new Message();
                    message.what = LIST_NETWORK_OK;
                    handler.sendMessage(message);
                }

                @Override
                public void onFailure(Call<CategoryListItem> call, Throwable t) {
                    Log.e("Retrofit Error", t.toString());
                }
            });

        }

//        subscribe_items=new ArrayList<>();
//        for(int i=0;i< titleList.size();i++){
//            Subscribe_item subscribe_item=new Subscribe_item(this.getActivity());
//            subscribe_item.setData(titleList.get(i),summaryList.get(i),imageUrlList.get(i));
//            subscribe_items.add(subscribe_item);
//        }
//        SubscribeListAdapter adapter=new SubscribeListAdapter(this.getActivity(),R.layout.category_subscribe_item,subscribe_items);
//        subscribeList.setAdapter(adapter);
    }

    @Subscribe
    public void onEventMainThread(String string) {
        listFlush();
    }

}
